package bin_tree.leetcode;

import java.util.*;

/**
 * 中序遍历的迭代写法
 * @author yuisama
 * @date 2022/02/21 21:21
 **/
public class Num94_InOrderNonRecursion {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        // 当前走到的节点
        TreeNode cur = root;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while (cur != null || !stack.isEmpty()) {
            // 不管三七二十一，先一路向左走到根儿~
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 此时cur为空，说明走到了null，此时栈顶就存放了左树为空的节点
            cur = stack.pop();
            ret.add(cur.val);
            // 继续访问右子树
            cur = cur.right;
        }
        return ret;
    }
}